﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

using System.Web.Configuration;
namespace JULONG.WEB.Library
{
    public class webConfig
    {
        //打开配置文件
        static Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

        //appSettings节点
        static AppSettingsSection appSection;

        static webConfig()
        {
            //获取appSettings节点
            appSection = (AppSettingsSection)config.GetSection("appSettings");
        }
        
        public static string AppSettings(string key)
        {
            //var aa = WebConfigurationManager.GetSection("appSettings") as System.Configuration.KeyValueInternalCollection;
            return System.Configuration.ConfigurationManager.AppSettings[key];
        }

        public static T AppSettings<T>(string key, T defaultValue)
        {
            var val = AppSettings(key).ToString();
            if (string.IsNullOrWhiteSpace(val)) return defaultValue;
            return Utility.ConvertType<T>(val, defaultValue);
        }

        public static T AppSettings<T>(string key)
        {
            return AppSettings<T>(key, default(T));
        }

        public static void AppSettingSet(string key, string value)
        {
            if (string.IsNullOrEmpty(key)) throw new Exception("key非法！");
            if (string.IsNullOrEmpty(value)) throw new Exception("value非法！");


            ////打开配置文件
            //Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

            ////获取appSettings节点
            //AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");


            //如果存在
            if (appSection.Settings.AllKeys.Any(d => d == key))
            {
                appSection.Settings[key].Value = value;
            }
            else
            {
                appSection.Settings.Add(key, value);
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static void AppSettingRemove(string key)
        {
            appSection.Settings.Remove(key);
        }

    }
}
